# -*- coding: utf-8 -*-

import json

from django.utils.decorators import method_decorator
from django.utils.encoding import smart_unicode
from django.views.generic import TemplateView

from common.admin import db as user_db
from common.strategy import admin_db as strategy_db
from common.utils import track_logging
from common.utils.api import token_required
from common.utils.decorator import response_wrapper
from common.utils.tz import (
    utc_to_local_str
)

_LOGGER = track_logging.getLogger(__name__)


class StrategyView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        cond = user_db.get_mchids_filter_by_user(req.user_id)
        if cond and not query_dct.get('mch_id', ''):
            query_dct['mch_id'] = cond
        _LOGGER.info('StrategyView get mchs: %s, ', query_dct)
        items, total_count = strategy_db.list_strategy(query_dct)

        resp_items = []
        for item in items:
            data = item.as_dict()
            data['created_at'] = utc_to_local_str(data['created_at'])
            data['updated_at'] = utc_to_local_str(data['updated_at'])
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'size': len(resp_items), 'total_count': total_count}

    def post(self, req):
        param_dct = json.loads(req.body)
        chns = param_dct['chns']
        if chns and not chns.startswith(','):
            chns = ',' + chns
        if chns and not chns.endswith(','):
            chns = chns + ','
        param_dct['chns'] = chns
        strategy_db.upsert_strategy(param_dct)
        return {}

    def put(self, req):
        return self.post(req)

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(StrategyView, self).dispatch(*args, **kwargs)


class SingleStrategyView(TemplateView):
    def get(self, req, strategy_id):
        strategy = strategy_db.get_strategy(id=int(strategy_id))
        data = strategy.as_dict()
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        return data

    def post(self, req, strategy_id):
        return self.put(req, strategy_id)

    def put(self, req, strategy_id):
        query_dct = json.loads(smart_unicode(req.body))
        json.loads(query_dct['content'])
        chns = query_dct['chns']
        if chns and not chns.startswith(','):
            chns = ',' + chns
        if chns and not chns.endswith(','):
            chns = chns + ','
        query_dct['chns'] = chns
        strategy_db.upsert_strategy(query_dct, int(strategy_id))
        return {}

    def delete(self, req, strategy_id):
        strategy_db.delete_strategy(int(strategy_id))
        _LOGGER.info('delete strategy: %s, user: %s', strategy_id, req.user_id)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleStrategyView, self).dispatch(*args, **kwargs)
